Component({
  data: {
    selected: 0,
    color: "#999999",
    selectedColor: "#ff6b81",
    backgroundColor: "#ffffff",
    list: [
      {
        pagePath: "/pages/index/index",
        text: "首页",
        iconPath: "/static/images/icons/tab-home.png",
        selectedIconPath: "/static/images/icons/tab-home-active.png"
      },
      {
        pagePath: "/pages/category/index",
        text: "分类",
        iconPath: "/static/images/icons/tab-category.png",
        selectedIconPath: "/static/images/icons/tab-category-active.png"
      },
      {
        pagePath: "/pages/cart/index",
        text: "购物车",
        iconPath: "/static/images/icons/tab-cart.png",
        selectedIconPath: "/static/images/icons/tab-cart-active.png"
      },
      {
        pagePath: "/pages/my/index",
        text: "我的",
        iconPath: "/static/images/icons/tab-my.png",
        selectedIconPath: "/static/images/icons/tab-my-active.png"
      }
    ]
  },
  lifetimes: {
    attached() {
      console.log('自定义tabBar attached')
      
      this.setData({
        selected: this.getTabBarIndex()
      })
    },
    ready() {
      console.log('自定义tabBar ready')
    }
  },
  methods: {
    switchTab(e) {
      const data = e.currentTarget.dataset
      const url = data.path
      const index = data.index
      console.log('切换到页面:', url, '索引:', index)
      
      // 正常切换页面
      wx.switchTab({ url })
    },
    getTabBarIndex() {
      const pages = getCurrentPages()
      console.log('当前页面栈:', pages)
      
      if (!pages || pages.length === 0) {
        console.log('页面栈为空，默认选中首页')
        return 0
      }
      
      const currentPage = pages[pages.length - 1]
      const url = `/${currentPage.route}`
      console.log('当前页面路径:', url)
      
      const tabIndex = this.data.list.findIndex(item => item.pagePath === url)
      console.log('选中的tabBar索引:', tabIndex)
      return tabIndex !== -1 ? tabIndex : 0
    }
  }
}) 